<?php
session_start();

// 如用户未登录，直接点击进入此页面将强制跳转到登录界面
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// 处理发帖逻辑
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    $title = trim($_POST['title']);
    $content = trim($_POST['content']);

    // 验证输入
    if (empty($title) || empty($content)) {
        echo "<p style='color: red; text-align: center;'>标题和内容不能为空！</p>";
    } else {
        // 连接数据库
        $host = 'localhost';
        $db   = 'dev_community';
        $user = 'root'; // 请替换为您的数据库用户名
        $pass = 'root'; // 请替换为您的数据库密码
        $charset = 'utf8mb4';

        $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ];

        try {
            $pdo = new PDO($dsn, $user, $pass, $options);
        } catch (\PDOException $e) {
            die("数据库连接失败: " . $e->getMessage());
        }

        // 插入帖子内容到数据库
        $stmt = $pdo->prepare("INSERT INTO questions (user_id, title, content) VALUES (?, ?, ?)");
        $stmt->execute([$_SESSION['user_id'], $title, $content]);

        // 发帖成功后，重定向到帖子列表页面或显示成功消息
        header('Location: index.php');
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP开放社区-发帖</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
    <link rel="stylesheet" type="text/css" href="css/qs.css"/>
</head>

<body>
    <div class="panel">
        <div class="panel-heading">
            <h2>智界论坛</h2>
            <div class="header-actions">
                <div class="button-group">
                    <!-- 去掉注册登录等按钮 -->
                </div>
            </div>
        </div>
        <div class="form-container">
            <h3>发帖</h3>
            <form method="post" action="" enctype="multipart/form-data">
                <p>标题：<input type="text" name="title" required/></p>
                <p>内容：<textarea name="content" rows="18" required></textarea></p>
                <p><input type="submit" value="发表" name="submit" class="btn"></p>
            </form>
        </div>
        <div class="button-group" style="margin-top: 20px;">
            <a href="index.php" class="btn">返回主页</a>
        </div>
    </div>

    <!-- 添加网页尾部 -->
    <div class="footer">
        <p>&copy;  智界论坛·保留所有权利</p>
        <p>版权所有☆Qualan<sup>&copy;</sup> Q_L</p>
    </div>
</body>

</html>